﻿using System;
using System.IO;
using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.GZip;

namespace Czf_Serialize
{
	public static class CzfZipHelper
	{
		public static byte[] UnZip(byte[] bytes)
		{
			byte[] ret;
			using (GZipInputStream s = new GZipInputStream(new MemoryStream(bytes))) {
				ret = StreamToBytes (s);
				s.Close ();
			}
			return ret;
		}

		public static byte[] Zip(byte[] bytes)
		{
			byte[] ret;
			using (MemoryStream outStream = new MemoryStream ()) {
				using (GZipOutputStream s = new GZipOutputStream (outStream)) {
					s.Write (bytes, 0, bytes.Length);
					s.Close ();
					ret = outStream.ToArray ();
					outStream.Close ();
				}
			}

			return ret;
		}

		public static byte[] StreamToBytes(Stream stream)
		{
			byte[] buffer = new byte[1024];
			using (MemoryStream outStream = new MemoryStream ()) {
				while (true) 
				{
					int bytesRead = stream.Read(buffer, 0, buffer.Length); 
					if (bytesRead <= 0) 
					{
						break; 
					}
					outStream.Write (buffer, 0, bytesRead);
				}
				outStream.Position = 0;
				return outStream.ToArray();
			}
		}
	}
}

